package com.ming.demo.easyiot;

import android.app.AlertDialog;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.R.attr.format;
import static android.R.attr.lines;
import static android.R.attr.min;
import static android.media.CamcorderProfile.get;
import static android.provider.Telephony.Carriers.APN;
import static android.transition.Fade.IN;
import static com.amap.api.mapcore2d.p.i;

/**
 * Created by Administrator on 2018/1/8.
 */

public class HistoryAdapter extends RecyclerView.Adapter<HistoryAdapter.ViewHolder> implements View.OnClickListener {
    private Context context;
    private List<ServiceInfo> list;
    private List<Integer> selectList = new ArrayList();
    private Map positonList = new HashMap();
    private JSONArray deleteList;
    private PostUtil post;
    private int curposition = 0;

    public HistoryAdapter(Context context) {
        this.context = context;
    }

    public HistoryAdapter(Context context, List<ServiceInfo> list) {
        this.context = context;
        this.list = list;
        post = new PostUtil(context);
    }

    @Override
    public HistoryAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_history, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(HistoryAdapter.ViewHolder holder, int position) {
        int mposition = list.size() - position - 1;
        holder.mTvNote.setText(list.get(mposition).getPositionRemark());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String d = format.format(list.get(mposition).getTimeStamp());
        if (list.get(mposition).getIsSucceed() == 0) {
            holder.mTvState.setText("已上报");
        } else if (list.get(mposition).getIsSucceed() == 1) {
            holder.mTvState.setText("未上报");
        } else {
            holder.mTvState.setText("异常未上报");
        }
        holder.mTvTime.setText(d);
        holder.mCheckDelete.setTag(mposition);
        checkboxInit(holder.mCheckDelete, mposition);
        holder.mLyItem.setOnClickListener(this);
        holder.mLyItem.setTag(mposition);
    }

    @Override
    public int getItemCount() {
        if (list == null) {
            return 0;
        }
        return list.size();
    }

    @Override
    public void onClick(View view) {
        showDetailDialog((int) view.getTag());
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        CheckBox mCheckDelete;
        TextView mTvTime, mTvNote, mTvState;
        LinearLayout mLyItem;

        public ViewHolder(View itemView) {
            super(itemView);
            mCheckDelete = (CheckBox) itemView.findViewById(R.id.mCheckBoxDelete);
            mTvTime = (TextView) itemView.findViewById(R.id.mTvTime);
            mTvNote = (TextView) itemView.findViewById(R.id.mTvNote);
            mTvState = (TextView) itemView.findViewById(R.id.mTvState);
            mLyItem = (LinearLayout) itemView.findViewById(R.id.mLyItem);
        }
    }

    public void checkboxInit(CheckBox mCheckDelete, int position) {

        if (selectList.contains(position)) {
            mCheckDelete.setChecked(true);
        } else {
            mCheckDelete.setChecked(false);
        }
        mCheckDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CheckBox checkBox = (CheckBox) view;
                int index = (int) view.getTag();
                if (checkBox.isChecked()) {
                    selectList.add(index);
                    positonList.put(index, selectList.size() - 1);//记录删除选项的position存放在selectList里的下标
                } else {
                    selectList.remove(positonList.get(index));
                    positonList.remove(index);
                }
            }
        });
    }

    public void selectAll(int isSelectAll) {
        if (isSelectAll == 0) {
            selectList = new ArrayList();
            for (int i = 0; i < getItemCount(); i++) {
                selectList.add(i);
            }
        } else {
            selectList = new ArrayList();
        }
        notifyDataSetChanged();
    }

    public void update() {
        if (selectList != null & selectList.size() > 0) {
            deleteList = new JSONArray();
            for (int i = 0; i < selectList.size(); i++) {
                ServiceInfo info = list.get((int) selectList.get(i));
                JSONObject param = new JSONObject();
                try {
                    param.put("IMSI", info.getIMSI());//0
                    param.put("IMEI", info.getIMEI());//0
                    param.put("UEType", info.getUEType());
                    if (!StringUtil.isNull(info.getAPN()))
                        param.put("APN", info.getAPN());//1
                    param.put("RSRP", info.getRSRP());//1
                    if (info.getRSSI() != 0)
                        param.put("RSSI", info.getRSSI());//0
                    if (!StringUtil.isNull(info.getPCI()))
                        param.put("PCI", info.getPCI());//1
                    if (!StringUtil.isNull(info.getCellID()))
                        param.put("CellID", info.getCellID());//1
                    param.put("TXPower", info.getTXPower());//0
                    param.put("EARFCN", info.getEARFCN());//0
                    if (!StringUtil.isNull(info.getPositionCoordinates()))
                        param.put("PositionCoordinates", info.getPositionCoordinates());//1
                    param.put("Altitude", info.getAltitude());//0
                    param.put("ModelVersion", info.getModelVersion());//0
                    if (!StringUtil.isNull(info.getSNR()))
                        param.put("SNR", info.getSNR());//1
                    param.put("TimeStamp", info.getTimeStamp());//0
                    param.put("ReportType", info.getReportType());//0
                    param.put("PositionRemark", info.getPositionRemark());//1
                    if (info.getReportType() == 2)
                        param.put("PingReturnedValue", new JSONObject(info.getPingReturnedValue()));//1
                    deleteList.put(param);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            post.sumit(deleteList, null, this, selectList);


        } else {
            Toast.makeText(context, "请先选择上报的条目！", Toast.LENGTH_SHORT).show();
        }
    }

    public void delete() {
        if (selectList != null & selectList.size() > 0) {
            Collections.sort(selectList, new Comparator() {
                        @Override
                        public int compare(Object o, Object t1) {
                            int arg0 = (int) o;
                            int arg1 = (int) t1;
                            return new Integer(arg1).compareTo(new Integer(arg0));
                        }
                    }
            );
            for (int i = 0; i < selectList.size(); i++) {
                removeList((int) selectList.get(i));
                notifyDataSetChanged();
            }
            cleanList();

        } else {
            Toast.makeText(context, "请先选择删除的条目！", Toast.LENGTH_SHORT).show();
        }
    }

    public void removeList(int position) {
        int id = list.get(position).getId();
        list.remove(position);
        DataSupport.delete(ServiceInfo.class, id);
    }

    public void cleanList() {
        deleteList = new JSONArray();
        selectList = new ArrayList();
    }

    TextView mTvImei, mTvImsi, mTvUEType, mTvAPN, mTvRSRP, mTvRSSI, mTvPCI, mTvCellID, mTvTXPower, mTvEARFCN, mTvAltitude, mTvModelVersion, mTvSNR, mTvIPAddress, mTvReportType, mTvPositionRemark, mTvLat, mTvLon;

    public void setInfo() {
        ServiceInfo lastInfo = list.get(curposition);
        mTvImei.setText("IMEI:" + lastInfo.getIMEI());
        mTvImsi.setText("IMSI:" + lastInfo.getIMSI());
        mTvUEType.setText("UEType:" + lastInfo.getUEType());
        mTvAPN.setText("APN:" + lastInfo.getAPN());
        mTvRSRP.setText("RSRP:" + lastInfo.getRSRP());
        mTvRSSI.setText("RSSI:" + lastInfo.getRSSI());
        mTvPCI.setText("PCI:" + lastInfo.getPCI());
        mTvCellID.setText("CellID:" + lastInfo.getCellID());
        mTvTXPower.setText("TXPower:" + lastInfo.getTXPower());
        mTvEARFCN.setText("EARFCN:" + lastInfo.getEARFCN());
        mTvAltitude.setText("Altitude:" + lastInfo.getAltitude());
        mTvModelVersion.setText("ModelVersion:" + lastInfo.getModelVersion());
        mTvSNR.setText("SNR:" + lastInfo.getSNR());
        mTvIPAddress.setText("IPAddress:" + lastInfo.getIPAddress());
        mTvReportType.setText("ReportType:" + lastInfo.getReportType());
        mTvPositionRemark.setText("PositionRemark:" + lastInfo.getPositionRemark());

        try {
            String str = lastInfo.getPositionCoordinates();
            str = str.replace("+", "");
            mTvLon.setText("经度:" + str.split(",")[1]);
            mTvLat.setText("纬度:" + str.split(",")[0]);
        } catch (Exception ex) {
            mTvLon.setText("经度:0");
            mTvLat.setText("纬度:0");
        }
    }

    public void showDetailDialog(int position) {
        ServiceInfo lastInfo = list.get(position);
        curposition = position;
        final AlertDialog builder = new AlertDialog.Builder(context).create();
        builder.show();
        builder.getWindow().setContentView(R.layout.detail_dialog);
        builder.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        //一定得在show完dialog后来set属性
        WindowManager m = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        WindowManager.LayoutParams lp = builder.getWindow().getAttributes();
        lp.width = (int) (d.getWidth() * 0.9);
        builder.getWindow().setAttributes(lp);

        builder.setCancelable(true);
        GestureDemoView mLyDialog = (GestureDemoView) builder.getWindow().findViewById(R.id.mLyDialog);
        mLyDialog.setMyListener(context, onGestureListener);
        mTvImei = (TextView) builder.getWindow().findViewById(R.id.mTvImei);
        mTvImsi = (TextView) builder.getWindow().findViewById(R.id.mTvImsi);
        mTvUEType = (TextView) builder.getWindow().findViewById(R.id.mTvUEType);
        mTvAPN = (TextView) builder.getWindow().findViewById(R.id.mTvAPN);
        mTvRSRP = (TextView) builder.getWindow().findViewById(R.id.mTvRSRP);
        mTvRSSI = (TextView) builder.getWindow().findViewById(R.id.mTvRSSI);
        mTvPCI = (TextView) builder.getWindow().findViewById(R.id.mTvPCI);
        mTvCellID = (TextView) builder.getWindow().findViewById(R.id.mTvCellID);
        mTvTXPower = (TextView) builder.getWindow().findViewById(R.id.mTvTXPower);
        mTvEARFCN = (TextView) builder.getWindow().findViewById(R.id.mTvEARFCN);
        mTvAltitude = (TextView) builder.getWindow().findViewById(R.id.mTvAltitude);
        mTvModelVersion = (TextView) builder.getWindow().findViewById(R.id.mTvModelVersion);
        mTvSNR = (TextView) builder.getWindow().findViewById(R.id.mTvSNR);
        mTvIPAddress = (TextView) builder.getWindow().findViewById(R.id.mTvIPAddress);
        mTvReportType = (TextView) builder.getWindow().findViewById(R.id.mTvReportType);
        mTvPositionRemark = (TextView) builder.getWindow().findViewById(R.id.mTvPositionRemark);

        mTvLat = (TextView) builder.getWindow().findViewById(R.id.mTvLat);
        mTvLon = (TextView) builder.getWindow().findViewById(R.id.mTvLon);
        setInfo();
        LinearLayout dialog_ok = (LinearLayout) builder.getWindow().findViewById(R.id.mLyOk);
        dialog_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                builder.dismiss();
            }
        });
    }

    //初始化手势监听对象，使用GestureDetector.OnGestureListener的实现抽象类，因为实际开发中好多方法用不上
    private final GestureDetector.OnGestureListener onGestureListener = new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            Log.d("GestureDemoView", "onSingleTapUp() ");
            return super.onSingleTapUp(e);
        }

        @Override
        public void onLongPress(MotionEvent e) {
            Log.d("GestureDemoView", "onLongPress() ");
            super.onLongPress(e);
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            Log.d("GestureDemoView", "onScroll() distanceX = " + distanceX);
            return super.onScroll(e1, e2, distanceX, distanceY);
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            Log.d("GestureDemoView", "onFling() velocityX = " + velocityX);
            int size = list.size();
            if (e1.getX() - e2.getX() > 40) {
                if (curposition == 0) {
                    Toast.makeText(context, "已经是最后一条", Toast.LENGTH_LONG).show();
                } else {
                    curposition--;
                    setInfo();
                }
            }
            // 向下滑动
            if (e2.getX() - e1.getX() > 40) {
                if ((curposition == (size - 1))) {
                    Toast.makeText(context, "已经是第一条", Toast.LENGTH_LONG).show();
                } else {
                    curposition++;
                    setInfo();
                }

            }
            return super.onFling(e1, e2, velocityX, velocityY);
        }

        @Override
        public void onShowPress(MotionEvent e) {
            Log.d("GestureDemoView", "onShowPress() ");
            super.onShowPress(e);
        }

        @Override
        public boolean onDown(MotionEvent e) {
            Log.d("GestureDemoView", "onDown() ");
            return super.onDown(e);
        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            Log.d("GestureDemoView", "onDoubleTap() ");
            return super.onDoubleTap(e);
        }

        @Override
        public boolean onDoubleTapEvent(MotionEvent e) {
            Log.d("GestureDemoView", "onDoubleTapEvent() ");
            return super.onDoubleTapEvent(e);
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            Log.d("GestureDemoView", "onSingleTapConfirmed() ");
            return super.onSingleTapConfirmed(e);
        }

        @Override
        public boolean onContextClick(MotionEvent e) {
            Log.d("GestureDemoView", "onContextClick() ");
            return super.onContextClick(e);
        }
    };
}
